<?php

namespace app\admin\model\exchange;

use think\Model;


class Code extends Model
{

    

    

    // 表名
    protected $table = 'exchange_code';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
    

    /**
     * [ordersRefundFinish 退货返还]
     * @since  2022-10-11
     * @param  [type]     $order_id [description]
     * @return [type]               [description]
     */
    public function ordersRefundFinish($order_id)
    {
        $order = db('shopro_order_item')->where('order_id',$order_id)->find();
        // 提货券购买
        $exchangeLibrary = db('exchange_library')->where('goods_id',$order['goods_id'])->value('id');
        if ($exchangeLibrary) {
            $exchangeGoods = db('exchange_goods')->where('library_id',$exchangeLibrary)->where('user_id',$order['user_id'])->find();
            if ($exchangeGoods) {
                // 退回记录
                unset($exchangeGoods['id']);
                $exchangeGoods['createtime'] = time();
                $exchangeGoods['remarks'] = '退货退回';
                $exchangeGoods['money'] = $exchangeGoods['money'] / $exchangeGoods['num'];
                $exchangeGoods['type'] = 2;
                $exchangeGoods['num'] = 1;
                db('exchange_goods')->insert($exchangeGoods);
            }
        }
        $this->where(['order_id'=>$order_id])->update(['order_id'=>0,'status'=>1]);
    }

    public function library()
    {
        return $this->belongsTo('Library', 'library_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
